package com.stargis.ftpdown;

import io.minio.*;
import io.minio.http.Method;

import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.concurrent.TimeUnit;

public class MinioTest {
    public static void main(String[] args) throws Exception {

        String endpoint = "http://111.33.173.130:9804";
        String accessKey = "Ap6H4QpQxhH1Ox5OdTwS";
        String secretKey = "193PyKj1ooa7LXnsFeaxqbff5ZRfzOVYrpc5uf8b";
        String bucketName = "jsjg";
        String objectName = "夔门2.png"; // 文件在桶中的名称，如：test.txt
        String filePath = "d:/夔门2.png"; // 本地文件路径

        MinioClient minioClient = MinioClient.builder()
                .endpoint(endpoint)
                //.endpoint("http://10.152.133.4:9804")
                .credentials(accessKey, secretKey)
                .build();

        String url = minioClient.getPresignedObjectUrl(
                GetPresignedObjectUrlArgs.builder()
                        .method(Method.GET)
                        .bucket(bucketName)
                        .object("夔门.png")
                        .expiry(1, TimeUnit.HOURS)  // 1小时有效期
                        .build());
        System.out.println("临时访问链接: " + url);

        // 确保存储桶存在，如果不存在则创建它
        boolean isExist = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        if (!isExist) {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
        } else {
            System.out.println("Bucket already exists.");
        }

        // 使用try-with-resources自动关闭流
        try (InputStream inputStream = Files.newInputStream(Paths.get(filePath))) {
            // 上传文件到存储桶中，使用默认选项（例如：默认的Content-Type）
            minioClient.putObject(
                    PutObjectArgs.builder()
                            .bucket(bucketName)
                            .object(objectName)
                            .stream(inputStream, inputStream.available(), -1) // 文件流和大小信息
                            .contentType("application/octet-stream") // 可选：指定Content-Type，例如：application/octet-stream表示二进制流，text/plain表示文本等。根据需要选择。
                            .build()
            );
            System.out.println("File uploaded successfully.");
        } catch (Exception e) {
            System.err.println("Error occurred: " + e.getMessage());
            throw e; // 可选：重新抛出异常或处理它。
        }

    }
}